package com.example.xmlfactory.parse.dom;

import com.example.xmlfactory.parse.ClassMsg;
import com.example.xmlfactory.parse.Serializer;
import com.example.xmlfactory.parse.Var;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.io.StringWriter;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 * Created by huangbei on 2017/9/12.
 */

public class DomSerializer implements Serializer{

    @Override
    public String serialize(Object obj) {
        try{
            ClassMsg classMsg = new ClassMsg(obj);

            //创建文档
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.newDocument();   //由builder创建新文档

            //组装节点
            Element root = doc.createElement(classMsg.getClassName());
            Map<String,Var> properties = classMsg.getProperties();
            Set<String> keys = properties.keySet();
            for(String key : keys){
                Element element = doc.createElement(key);
                element.setTextContent(properties.get(key).getValue().toString());
                root.appendChild(element);
            }
            doc.appendChild(root);

            //转换成string
            TransformerFactory transFactory = TransformerFactory.newInstance();//取得TransformerFactory实例
            Transformer transformer = transFactory.newTransformer();    //从transFactory获取Transformer实例
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");            // 设置输出采用的编码方式
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");                // 是否自动添加额外的空白
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");   // 是否忽略XML声明
            StringWriter writer = new StringWriter();
            Source source = new DOMSource(doc); //表明文档来源是doc
            Result result = new StreamResult(writer);//表明目标结果为writer
            transformer.transform(source, result);  //开始转换

            return writer.toString();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
